//index.js
import * as echarts from '../../../../ec-canvas/echarts';
//获取应用实例
const app = getApp()
var indexJson = require('../../../../data/indexJson');
var navListJson = require('../../../../data/navListJson');
var util = require('../../../../utils/healthUtil.js');
let PieChart = null;
let BarChart = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    btnTxt: {
      btnTxt: '记录体重'
    },
    ec: {
      // lazyLoad: true // 延迟加载
    },
    ec2: {
      // lazyLoad: true // 延迟加载
    },
    currentTab: 0,//当前页面
    progressLineList: [
      {
        left: 105,
      },
      {
        left: 120,
      },
      {
        left: 130,
      },
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (res) {
    var that = this
    if (!app.globalData.userInfo) {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      app.userInfoReadyCallback = res => {
        if (res) {
          that.setData({
            userInfo: res.userInfo
          });
        }
      }
    }else{
      this.setData({
        userInfo: app.globalData.userInfo
      })
    }
    that.setData({
      date: util.setTime7(new Date()),
      moduleList: indexJson.moduleList,
      navList: navListJson.indexNavList,
      themeColor: app.globalData.themeColor2
    })
    // that.getWxSportScope()  
      // that.getData()
  },

  //授权登录
  unLoginBtn:function(){
    var that = this
    if(app.globalData.userInfo){
      that.setData({
        userInfo: app.globalData.userInfo
      })
    }else{
      let isLogin = app.globalData.userId?true:false 
      //未授权
      wx.navigateTo({
        url: '/pages/authorizedLogin/authorizedLogin?isLogin='+ isLogin,
      })
    }
  },
  
  //获取数据
  getData:function(){
    var that = this;
    // 发送请求
    wx.request({
      url: app.globalData.apiUrl +'/get_user_startweight', //接口地址
      data: {
        id: that.data.userId
      },
      method: 'get',
      header: {
          'content-type': 'application/json' //默认值
      },
      success: function (res) {
        console.log(res)
        //判断用户是否存在
        if(res.data.code == 1){
          //后台有数据
          // console.log(app.globalData.userId);
          that.getIndexData();
          that.getWxSportScope();
          // that.judgeIsActivity()
        }else if(res.data.code == 0){
          //用户没有登录过 但是已经授权
          wx.redirectTo({
            url: '/subPages/healthData/login/login'
          })
        }
      }
    })
  },

  //获取微信运动授权
  getWxSportScope:function(){
    var that = this
    if(!app.globalData.isWeRun){
      wx.getSetting({
        success: function (res) {
          if (!res.authSetting['scope.werun']){
            wx.authorize({
              scope:'scope.werun',
              success(res) {
                app.globalData.isWeRun = true
                that.getWxSportData()
              }
            })
          }
        }
      })
    }else{
      that.getWxSportData()
    }
  },

  //获取微信运动数据
  getWxSportData:function(){
    var that = this
    wx.login({
      success: function(login){
        wx.getWeRunData({
          success: function (res) {
            // console.log(res);
            wx.request({
              url: app.globalData.apiUrl +'/Api/GetUser/ceshi', //接口地址
              data: {
                encryptedData: encodeURIComponent(res.encryptedData),
                iv: encodeURIComponent(res.iv),
                code:  login.code
              },
              method: 'get',
              header: {
                  'content-type': 'application/json' //默认值
              },
              success: function (res) {
                // console.log(res)
                var sportList = res.data.stepInfoList
                for(var i in sportList){
                  sportList[i].timestamp = util.setTime9(sportList[i].timestamp)
                }
                that.setData({
                  sportList: sportList
                })
                // console.log(that.data.sportList)
                that.getSportData(that.data.sportList[that.data.sportList.length - 1])
              }
            })
          },
          fail: function (err) {
            wx.showModal({
              title: '提示',
              content: '开发者未开通微信运动，请关注“微信运动”公众号后重试',
              showCancel: false,
              confirmText: '知道了'
            })
          }
        })
      }
    })
  },

  //获得运动记录
  getSportData:function(sport){
    var that = this;
    if(sport){
      var exerciseList = indexJson.exerciseList;
      for(let i in exerciseList){
        switch (exerciseList[i].index) {
          case 1:
            exerciseList[i].data = sport.step
            break;
          case 2:
            exerciseList[i].data = util.kcal(that.data.currentWeight,sport.step)
            break;
          // case 3:
          //   exerciseList[i].data = util.ChangeHourMinutestr(sport.time)
          //   break;
        }
      }
      that.setData({
        exerciseList: exerciseList
      })
    }else{
      that.setData({
        exerciseList: indexJson.exerciseList2
      })
    }
  },

  //运动按钮
  sport:function(){
    var that = this
    if(app.globalData.isWeRun){
      let sportList = JSON.stringify(that.data.sportList)
      // console.log(sportList)
      wx.navigateTo({
        url: '/subPages/healthData/sport/sport?sportList=' + sportList + '&weight=' +  that.data.currentWeight
      })
    }else{
      wx.showModal({
        title: '提示',
        content: '请重新授权微信运动',
        showCancel: true,
        success:res=>{
          // console.log(res)
          if(res.confirm){
            wx.openSetting({
              success(settingdata) {
                // console.log("settingdata", settingdata)
                if (settingdata.authSetting['scope.werun']) {
                  util.showModal('提示','获取权限成功,重新点击运动记录')
                  app.globalData.isWeRun = true
                } else {
                  util.showModal('提示','获取权限失败，将无法获取到运动数据~')
                }
              },
              fail(err) {
                // console.log("err",err)
              }
            })
          }
        }
      })
    }
  },

  judgeIsOne:function(){
    var that = this
  },

  judgeIsActivity:function(){
    var that = this
    wx.request({
      url: app.globalData.apiUrl +'/yes_no', //接口地址
      data: {
      },
      method: 'get',
      header: {
          'content-type': 'application/json' //默认值
      },
      success: function (res) {
        // console.log(res)
        var isGY = res.data=='yes'?true:false
        //判断是否第一次进入
        var dateStorage = wx.getStorageSync("date")
        if(dateStorage){
          if(dateStorage != that.data.date){
            //时间不等
            wx.setStorageSync("date", that.data.date)
            that.setData({
              isActivity: true,
              isGYActivity: isGY
            })
          }
        }else{
          wx.setStorageSync("date", that.data.date)
          that.setData({
            isActivity: true,
            isGYActivity: isGY
          })
        }
      },
      fail: function (res) {
        util.showModal('提示','读取活动图片失败')
      }
    })
  },

  //获得数据
  getIndexData:function(){
    var that = this
    wx.request({
      url: app.globalData.apiUrl +'/first_content', //接口地址
      data: {
        userid: that.data.userId,
        yes: that.data.date
      },
      method: 'get',
      header: {
          'content-type': 'application/json' //默认值
      },
      success: function (res) {
        console.log(res)
        if(res.data.code == '200'){
          that.getModuleData(res.data.data.is_show,res.data.data.is_head,res.data.data.is_qx);
          that.getWeightData(res.data.data.weight);
          that.getscalesData(res.data.data.tzc);
          that.getFootData(res.data.data.foot);
          // that.getSportData(res.data.data.sport);
          that.getBloodData(res.data.data.blood);
          that.getSugarData(res.data.data.sugar);
          that.getFatData(res.data.data.sugarfat);
        }else{
          util.showModal('提示','数据异常')
          return;
        }
      }
    })
  },

  //计算体重
  getWeightData:function(weight){
    var that = this
    if(weight){
      that.setData({
        currentWeight: weight.weight?weight.weight:0,//当前体重
        startWeight: weight.startweight,//初始体重
        targetWeight: weight.targetweight,//目标体重
        bmi: weight.bmi,
        bmiTip: that.setBmi(weight.bmi)[0],
        bmiColor: that.setBmi(weight.bmi)[1],
      })
      that.setPercent(weight)
      // console.log(that.data.percent)
     
    }else{
      that.setData({
        currentWeight: 0,//当前体重
        startWeight: 0,//初始体重
        targetWeight: 0,//目标体重
        bmi: 0,
        percent: 0
      })
    }
  },

  setPercent:function(weight){
    var that = this
    var percent = 0
    if(weight.weight && weight.weight != 0){
      if(weight.weight >= weight.startweight){
        percent = 0
      }else{
        percent = 100 - ((((weight.weight - weight.targetweight) / (weight.startweight  - weight.targetweight)).toFixed(1)) * 100);
      }
    }
    that.setData({
      percent: percent
    })
    if(that.data.percent && that.data.percent!= 0){
      that.anim(that.data.percent);
    }
  },

  //设置BMI
  setBmi:function(bmi){
    var arr = []
    var bmiTip = ''
    var bmiColor = ''
    if(bmi < 18.5){
      bmiTip = '偏低'
      bmiColor = '#49bdf9'
    }
    if(bmi >= 18.5 && bmi < 24){
      bmiTip = '正常'
      bmiColor = '#1fab57'
    }
    if(bmi >= 24 && bmi < 27){
      bmiTip = '轻度肥胖'
      bmiColor = '#f5bc51'
    }
    if(bmi > 27 && bmi <= 32){
      bmiTip = '肥胖'
      bmiColor = '#fa8b20'
    }
    if(bmi > 32){
      bmiTip = '重度肥胖'
      bmiColor = '#d65e5d'
    }
    arr.push(bmiTip,bmiColor)
    return arr
  },

  //获得人体成分数据
  getscalesData: function(list){
    var that = this
    if(list && list.arr.length!=0){
      // var data = []
      // data.push(list.bmi,list.bodyfat,list.protein,(list.bmr)/10,list.musclemass,list.visceralfatrate,list.watercontent,list.skeletoncontent)
      var arr = list.arr.bz.concat(list.arr.height).concat(list.arr.low)
      that.setData({
        // scalesList : data,
        bodyAge: list.bodyage,
        bodyAgeTip: that.setbodyAgeTip(list.bodyage,arr)[0],
        bodyAgeColor: that.setbodyAgeTip(list.bodyage,arr)[1],
        isScalesData: true
      })
      that.setScalesProgress(indexJson.scalesList,arr)
      // if(that.data.isBodyAge){
      //   that.getPieGraphData();        
      // }
      // if(that.data.isScales){
      //   that.getBarGraphData();
      // }
    }else{
      that.setData({
        isScalesData: false,
        bodyAge: 0,
        tipTxt: {
          tipTxt: '暂无测量数据',
          tipImg: '/resources/healthData/index/noDataWhite.png'
        }
      })
    }
  },

  //设置人体成分进度条
  setScalesProgress:function(scalesList,arr){
    // console.log(arr)
    var that = this
    var length = ''
    var color = ''
    var value = ''
    var maxLength = ''
    for(var s in scalesList){
      switch (scalesList[s].title) {
        case 'BMI':
          for(let i in arr){
            if(scalesList[s].title == arr[i].title){
              length = (Number(arr[i].value/32).toFixed(2)) * 100
              color = that.setScalesColor(arr[i].value,arr[i].best)
              value = arr[i].value
            }
          }
          scalesList[s].length = length
          scalesList[s].color = color
          scalesList[s].value = value
          scalesList[s].unit = util.setUnit(scalesList[s].text)
          break;
        case '体脂率':
          for(let i in arr){
            if(scalesList[s].title == arr[i].title){
              maxLength = arr[i].best[3].key + (arr[i].best[3].key - arr[i].best[2].key)
              length = (Number(arr[i].value/maxLength).toFixed(2)) * 100
              color = that.setScalesColor(arr[i].value,arr[i].best)
              value = arr[i].value
            }
          }
          scalesList[s].length = length
          scalesList[s].color = color
          scalesList[s].value = value
          scalesList[s].unit = util.setUnit(scalesList[s].text)
          break;
        case '蛋白质率':
          for(let i in arr){
            if(scalesList[s].title == arr[i].title){
              maxLength = arr[i].best[1].key + arr[i].best[0].key
              length = (Number(arr[i].value/maxLength).toFixed(2)) * 100
              color = that.setScalesColor(arr[i].value,arr[i].best)
              value = arr[i].value
            }
          }
          scalesList[s].length = length
          scalesList[s].color = color
          scalesList[s].value = value
          scalesList[s].unit = util.setUnit(scalesList[s].text)
          break;
        case '基础代谢':
          for(let i in arr){
            if(scalesList[s].title == arr[i].title){
              maxLength = (Number(arr[i].best[0].key)) * 2
              length = (Number(arr[i].value/maxLength).toFixed(2)) * 100
              color = that.setScalesColor(arr[i].value,arr[i].best)
              value = arr[i].value
            }
          }
          scalesList[s].length = length
          scalesList[s].color = color
          scalesList[s].value = value
          scalesList[s].unit = util.setUnit(scalesList[s].text)
          break;
        case '肌肉量':
          for(let i in arr){
            if(scalesList[s].title == arr[i].title){
              maxLength = arr[i].best[1].key + arr[i].best[0].key
              length = (Number(arr[i].value/maxLength).toFixed(2)) * 100
              color = that.setScalesColor(arr[i].value,arr[i].best)
              value = arr[i].value
            }
          }
          scalesList[s].length = length
          scalesList[s].color = color
          scalesList[s].value = value
          scalesList[s].unit = util.setUnit(scalesList[s].text)
          break;
        case '内脏脂肪':
          for(let i in arr){
            if(scalesList[s].title == arr[i].title){
              maxLength = arr[i].best[2].key + (arr[i].best[2].key - arr[i].best[1].key)
              length = (Number(arr[i].value/maxLength).toFixed(2)) * 100
              color = that.setScalesColor(arr[i].value,arr[i].best)
              value = arr[i].value
            }
          }
          scalesList[s].length = length
          scalesList[s].color = color
          scalesList[s].value = value
          scalesList[s].unit = util.setUnit(scalesList[s].text)
          break;
        case '水分率':
          for(let i in arr){
            if(scalesList[s].title == arr[i].title){
              maxLength = arr[i].best[1].key +  arr[i].best[0].key
              length = (Number(arr[i].value/maxLength).toFixed(2)) * 100
              color = that.setScalesColor(arr[i].value,arr[i].best)
              value = arr[i].value
            }
          }
          scalesList[s].length = length
          scalesList[s].color = color
          scalesList[s].value = value
          scalesList[s].unit = util.setUnit(scalesList[s].text)
          break;
        case '骨量':
          for(let i in arr){
            if(scalesList[s].title == arr[i].title){
              maxLength = arr[i].best[1].key + arr[i].best[0].key
              length = (Number(arr[i].value/maxLength).toFixed(2)) * 100
              color = that.setScalesColor(arr[i].value,arr[i].best)
              value = arr[i].value
            }
          }
          scalesList[s].length = length
          scalesList[s].color = color
          scalesList[s].value = value
          scalesList[s].unit = util.setUnit(scalesList[s].text)
          break;
      }
    }
    that.setData({
      scalesList: scalesList,
    })
    // for(var j in that.data.scalesList){
    //   let anim = that.data.scalesList[j].anim
    //   that.anim2(that.data.scalesList[j].length)
    // }
  },

  //动画 计算进度条
  anim2:function(length){
    var that = this
    var animation = wx.createAnimation({
      duration: 10000,  //动画时长
      timingFunction: 'linear', //线性
      delay: 0  //0则不延迟
    });
    // 第2步：这个动画实例赋给当前的动画实例

    animation.width(length + '%').step()
    // console.log(animation)
    that.setData({
      animationData2: animation.export()
    })
  },

  //设置称进度条颜色
  setScalesColor:function(data,best){
    var color = ''
    if(best.length == 2)
    {
      if(data < best[0].key)
      {
        color = '#49bdf9'
      }
      if(data >= best[0].key)
      {
        color = '#1fab57'
      }
    }
    if(best.length == 3)
    {
      if(data < best[0].key)
      {
        color = '#49bdf9'
      }
      if(data >= best[0].key && data < best[1].key)
      {
        color = '#1fab57'
      }
      if(data >= best[1].key)
      {
        color = '#f5bc51'
      }
    }
    if(best.length == 4 || best.length == 5)
    {
      if(data < best[0].key)
      {
        color = '#49bdf9'
      }
      if(data >= best[0].key && data < best[1].key)
      {
        color = '#1fab57'
      }
      if(data >= best[1].key && data < best[2].key)
      {
        color = '#f5bc51'
      }
      if(data >= best[2].key)
      {
        color = '#fa8b20'
      }
    }
    return color
  },

  //设置身体年龄
  setbodyAgeTip:function(bodyAge,arr){
    var list = []
    var bodyAgeTip = ''
    var bodyAgeColor = ''
    for(var i in arr){
      if(arr[i].title == '体年龄')
      if(bodyAge < arr[i].best){
        bodyAgeTip = '年轻' 
        bodyAgeColor = '#49bdf9'
      }
      if(bodyAge > arr[i].best){
        bodyAgeTip = '偏大' 
        bodyAgeColor = '#f5bc51'
      }
      if(bodyAge == arr[i].best){
        bodyAgeTip = '正常' 
        bodyAgeColor = '#1fab57'
      }
    }
    list.push(bodyAgeTip,bodyAgeColor)
    return list
  },

  //获得饮食记录
  getFootData:function(foot){
    var that = this
    if(foot.length != 0){
      for(let i in foot)
      {
        if(foot[i].date){
          that.setData({
            footTime: foot[i].date
          })
        }
        switch (foot[i].type) {
          case '1':
            that.setData({
              breakfastPicList: foot[i].img_url,
            })
            break;
          case '2':
            that.setData({
              lunchPicList: foot[i].img_url,
            })
            break;
          case '3':
            that.setData({
              dinnerPicList: foot[i].img_url,
            })
            break;
          // case '4':
          //   that.setData({
          //     snacksPicList: foot[i].img_url,
          //   })
          //   break;
        }
      }
    }else{
      that.setData({
        breakfastPicList: [],
        lunchPicList: [],
        dinnerPicList: [],
        snacksPicList: [],
        footTime: that.data.date
      })
    }
  },

  //获得血压数据
  getBloodData:function(blood){
    var that = this
    if(blood){
      that.setData({
        bloodHeight: blood.height,
        bloodLow: blood.low,
        bloodHeart: blood.heart,
        bloodTime: util.setTime8(blood.createtime)
      })
    }else{
      that.setData({
        bloodHeight: '-',
        bloodLow: '-',
        bloodHeart: '-',
        bloodTime: that.data.date
      })
    }
  },

  //获得血糖数据
  getSugarData:function(sugar){
    var that = this
    that.setData({
      isCount: sugar.count>0?true:false
    })
    if(sugar.list.length != 0){
      var sugarList = indexJson.sugarList
      for(let i in sugar.list){
        let item = sugar.list[i]
        switch (item.type) {
          case '1':
            sugarList[0].data = item.blood
            break;
          case '2':
            sugarList[1].data = item.blood
            break;
          case '3':
            sugarList[2].data = item.blood
            break;
          case '4':
            sugarList[3].data = item.blood
            break;
          case '5':
            sugarList[4].data = item.blood
            break;
          case '6':
            sugarList[5].data = item.blood
            break;
        }
      }
      that.setData({
        sugarList: sugarList
      })
    }else{
      that.setData({
        sugarList: indexJson.sugarList,
      })
    }
  },

  //获得血脂数据
  getFatData:function(fat){
    var that = this
    if(fat){
      var fatList = indexJson.fatList
      for(let i in fatList)
      {
        switch (fatList[i].index) {
          case 1:
            fatList[i].data = fat.cholesterol
            break;
          case 2:
            fatList[i].data = fat.glycerol
            break;
          case 3:
            fatList[i].data = fat.uric
            break;
          case 4:
            fatList[i].data = fat.hdl
            break;
          case 5:
            fatList[i].data = fat.ldl
            break;
        }
      }
      that.setData({
        fatList: fatList
      })
    }else{
      that.setData({
        fatList: indexJson.fatList2
      })
    }
  },

  //动画 计算进度条
  anim:function(percent){
    var that = this
    var animation = wx.createAnimation({
      duration: 200,  //动画时长
      timingFunction: 'linear', //线性
      delay: 0  //0则不延迟
    });
    // 第2步：这个动画实例赋给当前的动画实例
    that.animation = animation;
    animation.translateX(250 * (percent.toFixed(1) / 100)).step()
    // console.log(animation)
    that.setData({
      ifPercent: true,
      animationData: animation.export()
    })
  },

  //饼状图表
  // getPieGraphData:function(){
  //   // if(data == null || time == null) return;
  //   var that = this
  //   if (!PieChart){
  //     that.init_pieEcharts(); //初始化图表
  //   }else{
  //     that.setPieOption(); //更新数据
  //   }
  // },

  // //初始化图表
  // init_pieEcharts: function () {
  //   var that = this
  //   that.piechartsComponnet = that.selectComponent('#mychartPie');    
  //   that.piechartsComponnet.init((canvas, width, height) => {
  //     // 初始化图表
  //     PieChart = echarts.init(canvas, null, {
  //       width: width,
  //       height: height
  //     });
  //     PieChart.showLoading({
  //       text : '正在努力的读取数据中...'
  //     });
  //     // PieChart.setPieOption(this.getBarOption());
  //     that.setPieOption();
  //     // 注意这里一定要返回 chart 实例，否则会影响事件处理等
  //     return PieChart;
  //   });
  // },

  // setPieOption: function () {
  //   PieChart.clear();  // 清除
  //   PieChart.setOption(this.getPieOption());  //获取新数据
  // },

  // //设置饼状图表
  // getPieOption: function () {
  //   var that = this 
  //   var data = that.data.bodyAge
  //   // 指定图表的配置项和数据
  //   var option = {
  //     // tooltip: {
  //     //   trigger: 'item',
  //     //   formatter: "{b}: {c} "
  //     // },
  //     series : [{
  //       name:'',
  //       type:'pie',
  //       radius: ['60%', '90%'],
  //       center: ['50%', '50%'],
  //       hoverAnimation: true,
  //       silent: true, //图形是否不响应和触发鼠标事件
  //       label: {
  //         normal: {
  //           position: 'center',
  //           show: true,
  //           height: 60
  //         }
  //       },
  //       itemStyle:{
  //         color: '#dddbdb',
  //         borderColor:'#fff',
  //         borderWidth: 2,
  //         borderType: 'solid'
  //       },
  //       data:[
  //         {
  //           value:data,
  //           name:'生理年龄',
  //           itemStyle:{
  //             color: '#50d2c2',
  //           },
  //           label:{
  //             normal:{
  //               formatter: [
  //                 '{num|{c}}',
  //                 '{score|SCORE}',
  //                 '{name|{b}}',
  //               ].join('\n'),
  //               rich: {
  //                 num: {
  //                   color: '#1d1d1d',
  //                   fontSize: 38,
  //                 },
  //                 score: {
  //                   color: '#d5d5d5',
  //                   fontSize: 12,
  //                   padding: [10,0]
  //                 },
  //                 name:{
  //                   color: '#707070',
  //                   fontSize: 18,
  //                 }
  //               }
  //             }
  //           }
  //         },{
  //           value:10,
  //           itemStyle:{
  //             color: '#dddbdb',
  //           }
  //         }
  //       ]
  //     }]
  //   };
  //   PieChart.hideLoading()
  //   return option;
  // },

  //柱状图表
  // getBarGraphData:function(){
  //   var that = this
  //   if (!BarChart){
  //     that.init_barEcharts(); //初始化图表
  //   }else{
  //     that.setBarOption(); //更新数据
  //   }
  // },

  // //初始化图表
  // init_barEcharts: function () {
  //   var that = this
  //   that.barchartsComponnet = that.selectComponent('#mychartBar');
  //   that.barchartsComponnet.init((canvas, width, height) => {
  //     // 初始化图表
  //     BarChart = echarts.init(canvas, null, {
  //       width: width,
  //       height: height
  //     });
  //     BarChart.showLoading({
  //       text : '正在努力的读取数据中...'
  //     });
  //     // BarChart.setBarOption(this.getBarOption());
  //     that.setBarOption();
  //     BarChart.on('click',{seriesIndex: 0},function(e){
  //       // console.log(e)
  //       wx.navigateTo({
  //         url: '/subPages/health/composition/composition?name=' + e.name
  //       })
  //     })
  //     // 注意这里一定要返回 BarChart 实例，否则会影响事件处理等
  //     return BarChart;
  //   });
  // },

  // setBarOption: function () {
  //   BarChart.clear();  // 清除
  //   BarChart.setOption(this.getBarOption());  //获取新数据
  // },

  // //设置柱状图表
  // getBarOption: function () {
  //   var that = this 
  //   // console.log(data)
  //   // 指定图表的配置项和数据
  //   var option = {
  //     grid:{ 
  //       borderWidth:0,
  //       x:10,
  //       y:10,
  //       x2:40,
  //       y2:10,
  //       containLabel: true
  //     },
  //     xAxis: { 
  //       type: 'log',
  //       show:true,
  //       axisLine:{
  //         show: false,
  //       },
  //       axisTick: {
  //         show: false,
  //       },
  //       axisLabel:{
  //         show: true,
  //         color: '#3b3a3a'
  //       },
  //       splitLine:{
  //         show: true,
  //         lineStyle:{
  //           color: '#9ed0ff'
  //         }
  //       },
  //       // data : ['偏低','正常','偏高','超重'],
  //       // max: 50,
  //     },
  //     yAxis: {
  //       type: 'category',
  //       show:true,
  //       inverse: true,
  //       axisLine:{
  //         show: true,
  //         lineStyle:{
  //           color: '#9ed0ff'
  //         }
  //       },
  //       axisTick: {
  //         show: true,
  //         lineStyle:{
  //           color: '#9ed0ff'
  //         }
  //       },
  //       axisLabel:{
  //         show: true,
  //         color: '#3b3a3a'
  //       },
  //       data : ['BMI','体脂率','体蛋白质','基础代谢','体肌肉量','内脏脂肪','水分率','骨矿含量'],
  //     },
  //     series : [{
  //       name:'',
  //       type:'bar',
  //       barWidth: 15,
  //       itemStyle : {
  //         normal: {
  //           color: function(params) {
  //             var colorList = [
  //               'green','#B5C334','#FCCE10','#E87C25','#27727B',
  //                '#FE8463','#9BCA63','#FAD860'
  //             ];
  //             return colorList[params.dataIndex]
  //           },
  //           label : {
  //             show: true,
  //             color: '#2a2a2a',
  //             position: 'right',
  //             fontSize: 10,
  //             formatter:function(params){
  //               // console.log(params)
  //               if(params.name == '基础代谢'){
  //                 params.value = params.value * 10
  //               }
  //               let unit  = util.setUnit(params.name)
  //               return params.value + unit;
  //             }
  //           }
  //         },
  //       },
  //       data: that.data.scalesList
  //     }]
  //   };
  //   BarChart.hideLoading()
  //   return option;
  // },

  //记录体重
  recordWeight:function(){
    var that = this
    wx.navigateTo({
      url: '/subPages/healthData/recordWeight/recordWeight?weight=' + that.data.currentWeight
    })
    // wx.navigateTo({
    //   url: '/subPages/health/recordSize/recordSize'
    // }) 
    // wx.navigateTo({
    //   url: '../login/login'
    // }) 
  },

  //体重记录
  recordSize:function(){
    var type = 1
    wx.navigateTo({
      url: '/subPages/healthData/recordSize/recordSize?type=' + type + '&weight=' +  this.data.currentWeight
    }) 
  },

  //减重管理
  management:function(e){
    var that = this
    wx.navigateTo({
      url: '/subPages/healthData/management/management?type=' + e.currentTarget.dataset.type + '&date=' +  e.currentTarget.dataset.date
    })
  },

  composition:function(e){
    var that = this
    // console.log(e)
    wx.navigateTo({
      url: '/subPages/healthData/composition/composition?name=' + e.currentTarget.dataset.name
    })
  },

  //获取模块
  getModuleData:function(showList,headList,isQx){
    var that = this
    if(isQx == 1){
      let list = showList.concat(headList)
      let arr = []
      for(var i in list){
        arr.push({'index': list[i]})
      }
      for(let h in headList){
        let type = ''
        switch (headList[h]) {
          case '1':
            type = 'scales'
            break;
          case '2':
            type = 'pressure'
            break;
          case '3':
            type = 'blood'
            break;
          case '4':
            type = 'foot'
            break;
          // case '5':
          //   type = 'prescription'
          //   break;
        }
        that.showHiden(type)
      }
      that.setData({
        moduleList: arr,
        moduleTitleList: indexJson.moduleTitleList,
      })
    }else{
      if(!that.data.moduleTitleList){
        that.setData({
          moduleTitleList: indexJson.moduleTitleList,
        })
      }
    }
    
  },

  //显隐
  showHiden:function(type){
    // console.log(type)
    var that = this
    switch (type) {
      // case 'bodyAge':
      //   if(that.data.isBodyAge){
      //     that.setData({
      //       isBodyAge: false
      //     })
      //   }else{
      //     that.setData({
      //       isBodyAge: true
      //     })
      //     if(that.data.isScalesData){
      //       PieChart = null;          
      //       that.getPieGraphData();
      //     }
      //   }
      //   break;
      case 'scales':
        if(that.data.isScales){
          that.setData({
            isScales: false
          })
        }else{
          that.setData({
            isScales: true
          })
          // if(that.data.isScalesData){
          //   BarChart = null;
          //   that.getBarGraphData();
          // }
        }
        break;
      // case 'sport':
      //   that.setData({
      //     isSport: that.data.isSport?false:true
      //   })
      //   break;
      case 'pressure':
        that.setData({
          isPressure: that.data.isPressure?false:true
        })
        break;
      case 'blood':
        that.setData({
          isBlood: that.data.isBlood?false:true
        })
        break;
      case 'foot':
        that.setData({
          isFoot: that.data.isFoot?false:true
        })
        break;
      // case 'prescription':
      //   that.setData({
      //     isPrescription: that.data.isPrescription?false:true
      //   })
      //   break;
    }
  },

  //改变显隐
  changeShowHiden:function(e){
    var that = this
    // console.log(e)
    that.showHiden(e.currentTarget.dataset.type)
  },

  //详情按钮
  details:function(e){
    // console.log(e)
    switch (e.currentTarget.dataset.type) {
      case 'foot':
        wx.navigateTo({
          url: '/subPages/healthData/recordFoot/recordFoot'
        })
        break;
      case 'pressure':
        wx.navigateTo({
          url: '/subPages/healthData/pressure/pressure'
        })
        break;
    }
  },

  //选择导航栏
  switchNav(event){
    var cur = event.currentTarget.dataset.current;      
    if (this.data.currentTab == cur) {
        return false;
    } else {
        this.setData({
            currentTab: cur
        })
    }
  },

  //血糖按钮
  sugar:function(){
    wx.navigateTo({
      url: '/subPages/healthData/sugar/sugar'
    })
  },

  //血脂按钮
  bloodFat:function(){
    wx.navigateTo({
      url: '/subPages/healthData/bloodFat/bloodFat'
    })
  },

  //个人资料
  profile:function(){
    wx.navigateTo({
      url: '/subPages/healthData/profile/profile'
    })
  },

  //内容滚动
  switchTab(event){
    var cur = event.detail.current;
    this.setData({
        currentTab: cur
    });
  }, 

  // //签到
  // signlnBtn:function(){
  //   wx.navigateTo({
  //     url: '/subPages/mine/signIn/signIn'
  //   })
  //   this.setData({
  //     isActivity: false
  //   })
  // },

  // activityBtn:function(){
  //   wx.navigateTo({
  //     url: '/subPages/mine/publicWelfare/publicWelfare'
  //   })
  //   this.setData({
  //     isActivity: false
  //   })
  // },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    that.setData({
      // isBodyAge:true,
      isScales: true,
      isFoot: true,
      // isSport:true,
      isPressure: true,
      isBlood: true,
      // isPrescription: true,
    })
    if(app.globalData.userId){
      that.setData({
        userId: app.globalData.userId
      })
      that.getData();
    }else{
      app.userIdCallback = userId => {
        if (userId != '') {
          that.setData({
            userId: userId
          });
          that.getData();
        }
      }
    }
  },

  //阻止穿透
  preventTouchMove: function () {
    // console.log('stop user scroll it!');
    return;
  },

  //关闭
  close:function(){
    this.setData({
      isActivity: false
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    PieChart = null;
    BarChart = null;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    PieChart = null;
    BarChart = null;
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    // if(res.from === 'button'){
    //   this.setData({
    //     isActivity: false
    //   })
    //   app.globalData.isOne = false
    // }
    // return {
    //   title: 'PAPN体重管理',
    //   path: 'pages/index/index',
    //   success: function(res) {
    //     res.shareTickets 
    //   },
    //   fail: function(res) {
    //     console.log(res)
    //   }
    // }
  }
})